<template>
  <div class="articles-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">文章管理</h2>
        <t-space>
          <t-button theme="primary" @click="handleCreateArticle">
            <template #icon><t-icon name="add" /></template>
            新增文章
          </t-button>
        </t-space>
      </div>
    </t-card>
    
    <!-- 搜索和筛选 -->
    <t-card class="filter-card">
      <t-form layout="inline" :data="searchForm" @reset="handleSearchReset" @submit="handleSearchSubmit">
        <t-form-item label="标题" name="keyword">
          <t-input
            v-model="searchForm.keyword"
            placeholder="请输入文章标题关键词"
            clearable
          />
        </t-form-item>
        <t-form-item label="分类" name="category">
          <t-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="primary" type="submit">
              <template #icon><t-icon name="search" /></template>
              搜索
            </t-button>
            <t-button theme="default" type="reset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-card>
    
    <!-- 文章列表表格 -->
    <t-card class="table-card">
      <t-table
        :data="articleList"
        :columns="columns"
        :row-key="rowKey"
        :loading="tableLoading"
        :pagination="pagination"
        :hover="true"
        @page-change="onPageChange"
      >
        <!-- 标题列 -->
        <template #title="{ row }">
          <div class="article-title">
            <t-tag v-if="row.isTop" theme="primary" variant="light" size="small" style="margin-right: 8px">置顶</t-tag>
            {{ row.title }}
          </div>
        </template>
        
        <!-- 分类列 -->
        <template #category="{ row }">
          <t-tag theme="default" variant="light">{{ getCategoryLabel(row.category) }}</t-tag>
        </template>
        
        <!-- 状态列 -->
        <template #status="{ row }">
          <t-tag :theme="row.status === 'published' ? 'success' : 'warning'">
            {{ row.status === 'published' ? '已发布' : '草稿' }}
          </t-tag>
        </template>
        
        <!-- 发布时间列 -->
        <template #publishTime="{ row }">
          {{ formatDate(row.publishTime) }}
        </template>
        
        <!-- 操作列 -->
        <template #operation="{ row }">
          <t-space>
            <t-link theme="primary" hover="color" @click="handleEditArticle(row)">编辑</t-link>
            <t-link theme="primary" hover="color" @click="handlePreviewArticle(row)">预览</t-link>
            <t-link
              theme="primary"
              hover="color"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'published' ? '下架' : '发布' }}
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              @click="handleToggleTop(row)"
            >
              {{ row.isTop ? '取消置顶' : '置顶' }}
            </t-link>
            <t-popconfirm
              content="确认删除该文章吗？该操作不可撤销。"
              @confirm="handleDeleteArticle(row)"
            >
              <t-link theme="danger" hover="color">删除</t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </t-card>
    
    <!-- 文章表单对话框 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="formMode === 'create' ? '新增文章' : '编辑文章'"
      width="800px"
      :footer="false"
      @close="resetForm"
    >
      <t-form
        ref="form"
        :data="formData"
        :rules="rules"
        :label-width="100"
        @submit="handleFormSubmit"
      >
        <t-form-item label="文章标题" name="title">
          <t-input v-model="formData.title" placeholder="请输入文章标题" />
        </t-form-item>
        <t-form-item label="文章分类" name="category">
          <t-select
            v-model="formData.category"
            placeholder="请选择文章分类"
            clearable
          >
            <t-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="文章封面" name="coverImage">
          <t-upload
            v-model="formData.coverImage"
            theme="image"
            accept="image/*"
            :before-upload="handleBeforeUpload"
            :max="1"
          >
            <template #tip>
              <p class="upload-tip">支持.jpg .jpeg .png格式，大小不超过2M</p>
            </template>
          </t-upload>
        </t-form-item>
        <t-form-item label="文章内容" name="content">
          <div class="editor-container">
            <div id="editor-container" style="height: 300px;"></div>
          </div>
        </t-form-item>
        <t-form-item label="摘要" name="summary">
          <t-textarea
            v-model="formData.summary"
            placeholder="请输入文章摘要，不超过200个字"
            :maxlength="200"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>
        <t-form-item label="发布状态" name="status">
          <t-radio-group v-model="formData.status">
            <t-radio value="draft">保存为草稿</t-radio>
            <t-radio value="published">立即发布</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="dialogVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">确定</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 预览对话框 -->
    <t-dialog
      v-model:visible="previewVisible"
      header="文章预览"
      width="800px"
      :footer="false"
    >
      <div class="article-preview" v-if="previewData">
        <h1 class="preview-title">{{ previewData.title }}</h1>
        <div class="preview-meta">
          <span class="category">{{ getCategoryLabel(previewData.category) }}</span>
          <span class="date">{{ formatDate(previewData.publishTime) }}</span>
        </div>
        <div class="preview-cover" v-if="previewData.coverImage">
          <img :src="previewData.coverImage" alt="文章封面" />
        </div>
        <div class="preview-content" v-html="previewData.content"></div>
      </div>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { PrimaryTableCol, TableRowData, PageInfo } from 'tdesign-vue-next'
import {
  getArticleList,
  getArticleDetail,
  createArticle,
  updateArticle,
  updateArticleStatus,
  setArticleTop,
  deleteArticle
} from '../../../api/content/articles'

// 表格列定义
const columns: PrimaryTableCol[] = [
  {
    colKey: 'title',
    title: '标题',
    width: 280,
    cell: 'title'
  },
  {
    colKey: 'category',
    title: '分类',
    width: 100,
    cell: 'category'
  },
  {
    colKey: 'status',
    title: '状态',
    width: 100,
    cell: 'status'
  },
  {
    colKey: 'publishTime',
    title: '发布时间',
    width: 160,
    cell: 'publishTime'
  },
  {
    colKey: 'readCount',
    title: '阅读数',
    width: 100
  },
  {
    colKey: 'operation',
    title: '操作',
    fixed: 'right',
    width: 240,
    cell: 'operation'
  }
]

// 表格数据和加载状态
const articleList = ref<TableRowData[]>([])
const tableLoading = ref(false)
const rowKey = 'id'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showJumper: true,
  pageSizeOptions: [10, 20, 50]
})

// 分类和状态选项
const categoryOptions = [
  { value: 'spot', label: '景点资讯' },
  { value: 'health', label: '养生知识' },
  { value: 'activity', label: '活动通知' },
  { value: 'notice', label: '系统公告' }
]

const statusOptions = [
  { value: 'published', label: '已发布' },
  { value: 'draft', label: '草稿' }
]

// 表单相关
const dialogVisible = ref(false)
const formMode = ref<'create' | 'edit'>('create')
const formData = reactive({
  id: '',
  title: '',
  category: '',
  coverImage: [],
  content: '',
  summary: '',
  status: 'draft'
})
const submitLoading = ref(false)

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入文章标题', type: 'error' }],
  category: [{ required: true, message: '请选择文章分类', type: 'error' }],
  content: [{ required: true, message: '请输入文章内容', type: 'error' }]
}

// 预览相关
const previewVisible = ref(false)
const previewData = ref<any>(null)

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return '--'
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 根据分类值获取分类名称
const getCategoryLabel = (value: string) => {
  const item = categoryOptions.find(item => item.value === value)
  return item ? item.label : value
}

// 获取文章列表
const fetchArticleList = async () => {
  tableLoading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const data: any = await getArticleList(params)
    articleList.value = data.list || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('获取文章列表失败', error)
  } finally {
    tableLoading.value = false
  }
}

// 页码变化处理
const onPageChange = (pageInfo: PageInfo) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  fetchArticleList()
}

// 搜索表单提交
const handleSearchSubmit = () => {
  pagination.current = 1
  fetchArticleList()
}

// 重置搜索表单
const handleSearchReset = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  searchForm.status = ''
  pagination.current = 1
  fetchArticleList()
}

// 创建文章
const handleCreateArticle = () => {
  formMode.value = 'create'
  dialogVisible.value = true
  resetForm()
}

// 编辑文章
const handleEditArticle = async (row: TableRowData) => {
  formMode.value = 'edit'
  dialogVisible.value = true
  
  try {
    const data = await getArticleDetail(row.id as string)
    formData.id = row.id as string
    formData.title = data.title
    formData.category = data.category
    formData.summary = data.summary
    formData.status = data.status
    formData.content = data.content
    
    if (data.coverImage) {
      formData.coverImage = [
        {
          url: data.coverImage,
          name: data.title,
          response: { url: data.coverImage },
        }
      ]
    } else {
      formData.coverImage = []
    }
    
    // 初始化富文本编辑器
    nextTick(() => {
      // 这里应该设置编辑器内容
      // if (editor) editor.setContent(data.content)
    })
  } catch (error) {
    console.error('获取文章详情失败', error)
    MessagePlugin.error('获取文章详情失败')
  }
}

// 预览文章
const handlePreviewArticle = async (row: TableRowData) => {
  try {
    const data = await getArticleDetail(row.id as string)
    previewData.value = data
    previewVisible.value = true
  } catch (error) {
    console.error('获取文章详情失败', error)
    MessagePlugin.error('获取文章详情失败')
  }
}

// 表单提交
const handleFormSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (!validateResult) return
  
  submitLoading.value = true
  
  try {
    // 处理表单数据
    const submitData: any = {
      title: formData.title,
      category: formData.category,
      summary: formData.summary,
      status: formData.status,
      content: formData.content // 实际上应该从编辑器获取
    }
    
    // 处理封面图片
    if (formData.coverImage?.length > 0) {
      const upload = formData.coverImage[0] as any
      submitData.coverImage = upload.url || (upload.response && upload.response.url)
    }
    
    if (formMode.value === 'create') {
      // 创建文章
      await createArticle(submitData)
      MessagePlugin.success('创建成功')
    } else {
      // 更新文章
      await updateArticle(formData.id, submitData)
      MessagePlugin.success('更新成功')
    }
    
    // 关闭对话框并刷新列表
    dialogVisible.value = false
    fetchArticleList()
  } catch (error) {
    console.error('保存文章失败', error)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.title = ''
  formData.category = ''
  formData.coverImage = []
  formData.content = ''
  formData.summary = ''
  formData.status = 'draft'
  
  // 重置编辑器
  nextTick(() => {
    // 这里应该重置编辑器内容
    // if (editor) editor.setContent('')
  })
}

// 上传图片前的检查
const handleBeforeUpload = (file: File) => {
  const isImage = /image\/(jpeg|png|jpg)/.test(file.type)
  if (!isImage) {
    MessagePlugin.warning('只能上传jpg/jpeg/png格式图片')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    MessagePlugin.warning('图片大小不能超过2MB')
    return false
  }
  
  return true
}

// 切换文章状态
const handleToggleStatus = async (row: TableRowData) => {
  try {
    const newStatus = row.status === 'published' ? 'draft' : 'published'
    await updateArticleStatus(row.id as string, newStatus)
    MessagePlugin.success(`文章已${newStatus === 'published' ? '发布' : '下架'}`)
    fetchArticleList()
  } catch (error) {
    console.error('更新文章状态失败', error)
  }
}

// 切换置顶状态
const handleToggleTop = async (row: TableRowData) => {
  try {
    await setArticleTop(row.id as string, !row.isTop)
    MessagePlugin.success(row.isTop ? '已取消置顶' : '已设为置顶')
    fetchArticleList()
  } catch (error) {
    console.error('更新置顶状态失败', error)
  }
}

// 删除文章
const handleDeleteArticle = async (row: TableRowData) => {
  try {
    await deleteArticle(row.id as string)
    MessagePlugin.success('文章已删除')
    
    // 如果删除后当前页没有数据了，返回上一页
    if (articleList.value.length === 1 && pagination.current > 1) {
      pagination.current--
    }
    
    fetchArticleList()
  } catch (error) {
    console.error('删除文章失败', error)
  }
}

// 页面加载时获取文章列表
onMounted(() => {
  fetchArticleList()
  
  // 初始化富文本编辑器
  // initEditor()
})
</script>

<style scoped>
.articles-page {
  padding: 16px;
}

.header-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.filter-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.article-title {
  display: flex;
  align-items: center;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.editor-container {
  border: 1px solid #dcdcdc;
  border-radius: 3px;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

/* 预览样式 */
.article-preview {
  padding: 16px;
}

.preview-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 16px;
}

.preview-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  color: #666;
  font-size: 14px;
}

.preview-cover {
  margin-bottom: 24px;
  text-align: center;
}

.preview-cover img {
  max-width: 100%;
  max-height: 300px;
  object-fit: cover;
}

.preview-content {
  line-height: 1.8;
}
</style> 